package com.es.elasticsearch.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.es.elasticsearch.dao.mysql.EmergencyPlanMapper;
import com.es.elasticsearch.model.item.AuthUserRecordInfo;
import com.es.elasticsearch.model.item.AuthUserRecords;
import com.es.elasticsearch.model.item.EmergencyRecordOrgResource;
import com.es.elasticsearch.model.item.TreeInfo;
import com.es.elasticsearch.service.IPlanManagementService;
import com.google.common.base.Joiner;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;


import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 预案管理service
 */
@Service
@Slf4j
public class PlanManagementService implements IPlanManagementService {


    @Autowired
    EmergencyPlanMapper emergencyPlanMapper;

    public static ArrayList<Integer> sonlist = new ArrayList<>();

    public static ArrayList<Integer> userIdlist = new ArrayList<>();
    /**
     * 新增预案
     *
     * @param paramMap
     * @return
     */
    @Override
    public Integer savePlan(Map<String, Object> paramMap) {
        emergencyPlanMapper.insertPlan(paramMap);
        Object id = paramMap.get("id");
        return Integer.valueOf(id.toString());
    }
/*

    */
/**
     * 保存授权记录列表
     *
     * @param planId
     * @param authUserRecordList
     * @return
     */

    public void saveAuthRecord(Integer planId, List<AuthUserRecordInfo> authUserRecordList) {

        List<EmergencyRecordOrgResource> list = new ArrayList<>();

        //循环
        for (AuthUserRecordInfo model : authUserRecordList){
             List<TreeInfo> treeInfos = model.getResourceInfos();
             List<TreeInfo> treeInfoList = model.getSubjectInfos();
             String authUserRecordName = model.getAuthUserRecordName();//授权名称
            //获取useriD
            List<Integer>  organizeIdList = new ArrayList<>();
            List<Integer>  userIdList = new ArrayList<>();


            for (int i=0;i<treeInfos.size();i++){
                EmergencyRecordOrgResource emergencyRecordOrgResource = new EmergencyRecordOrgResource();

                TreeInfo org  = treeInfos.get(i);

                TreeInfo user = treeInfoList.get(i);
                String userId = "";
                if (user.getIsResource() == 0){
                    //获取的是组织id
                    //根据组织id 获取最底层组织id集合
                    getId(user.getId());
                    organizeIdList.add(user.getId());
                    organizeIdList.addAll(userIdlist);
                    //查询useriD
                    userIdList.addAll(emergencyPlanMapper.getUserId(organizeIdList));
                     userId = Joiner.on(",").join(userIdList);
                }else{
                    //获取的是用户id
                    userId = String.valueOf(user.getId());
                }

                List<Integer> allOrgList = new ArrayList<>();
                //判断isRESOURECE = 0 （组织） he 1 （摄像机）
                if ( org.getIsResource() == 1){
                    emergencyRecordOrgResource = new EmergencyRecordOrgResource(
                            org.getParentId(), org.getIsResource(), org.getId()
                    );
                    //allOrg处理 (往上找)
                    //根据parentId 一层一层找
                    allOrgList = new ArrayList<>();
                    Integer fatherId = org.getParentId();
                    while ( true ) {
                        fatherId = emergencyPlanMapper.getfather(fatherId);
                        if(fatherId == 1){
                            break;
                        }
                        allOrgList.add(fatherId);
                    }
                    allOrgList.add(org.getParentId());
                }
                if (org.getIsResource() == 0){
                    emergencyRecordOrgResource = new EmergencyRecordOrgResource(
                            null, org.getIsResource(), org.getId()
                    );
                    //allOrg处理 (上下都找)
                    //往下 （树的深度便利）
                    getSon(org.getId());
                    allOrgList.add(org.getId());
                    allOrgList.addAll(sonlist);
                    //往上
                    Integer fatherId = org.getId();
                    while ( true ) {
                        fatherId = emergencyPlanMapper.getfather(fatherId);
                        if(fatherId == 1){
                            break;
                        }
                        allOrgList.add(fatherId);
                    }
                }


                emergencyRecordOrgResource.setPlanId(planId);
                emergencyRecordOrgResource.setAuthUserRecordName(authUserRecordName);
                emergencyRecordOrgResource.setUserId(userId);
                String str = Joiner.on(",").join(allOrgList);
                emergencyRecordOrgResource.setAllOrg(str);
                list.add(emergencyRecordOrgResource);
            }



             
             List<Integer> allOrgList = new ArrayList<>();
             for (TreeInfo item : treeInfos){
                 EmergencyRecordOrgResource emergencyRecordOrgResource = new EmergencyRecordOrgResource();

             }


        }

        //sql 落库 list

        Integer integer = emergencyPlanMapper.batchInsert(list);


    }


    public void getSon (Integer id){
        List<Integer> son = emergencyPlanMapper.getSon(id);
        if (CollectionUtils.isEmpty(son)){
            return ;
        }
        for (Integer sonId:son){
            sonlist.add(sonId);
            getSon(sonId);
        }
    }

    public void getId (Integer id){
        List<Integer> son = emergencyPlanMapper.getSon(id);
        if (CollectionUtils.isEmpty(son)){
            return ;
        }
        for (Integer sonId:son){
            userIdlist.add(sonId);
            getId(sonId);
        }
    }
    //351231407

    /**
     * 新增预案
     *
     * @param paramMap
     * @throws Exception
     */
    @Override
    public void addPlan(Map<String, Object> paramMap) throws Exception {


        //内部参数校验
        if(!checkUser((String) paramMap.get("authUserRecords"))){
            throw new Exception();
        }


        Integer planId = this.savePlan(paramMap);
        String authUserRecords = (String) paramMap.get("authUserRecords");

        // 如果授权记录列表不为空，将授权记录信息保存
        if (!StringUtils.isEmpty(authUserRecords) && planId != null) {
            List<AuthUserRecordInfo> authUserRecordInfos = formList(authUserRecords);
            this.saveAuthRecord(planId, authUserRecordInfos);
        }
    }

    public boolean checkUser(String authUserRecords){
        List<AuthUserRecordInfo> list=formList(authUserRecords);
        //两个校验 获取所有用户id
        List<Integer>  organizeIdList = new ArrayList<>();
        List<Integer>  userIdList = new ArrayList<>();
        Set<Integer>  userIdSet =  new HashSet<>();
        List<Integer>  userIdLists = new ArrayList<>();
        for (AuthUserRecordInfo model :list){
            List<TreeInfo> subjectInfos = model.getSubjectInfos();
            for (TreeInfo item :subjectInfos){
                if (item.getIsResource() == 0){
                    //获取的是组织id
                    //根据组织id 获取最底层组织id集合
                    getId(item.getId());
                    organizeIdList.add(item.getId());
                    organizeIdList.addAll(userIdlist);
                    //查询useriD
                    userIdList.addAll(emergencyPlanMapper.getUserId(organizeIdList));
                }else{
                    Integer userId  = item.getId();
                    userIdList.add(userId);
                }
            }
        }
        userIdSet.addAll(userIdList);
        if (userIdSet.size() != userIdList.size()){
            return false;
        }
        //查询数据库  userid重复问题
        for (Integer model : userIdList){
            Integer userIdforCheck = emergencyPlanMapper.getUserIdforCheck(model);
            if (userIdforCheck >= 1){
                return false;
            }
        }
        return  true;
    }

    public List<AuthUserRecordInfo>  formList(String authUserRecords) {
        List<AuthUserRecordInfo> authUserRecordInfoList=new ArrayList<>();
        JSONArray jsonArray = JSONObject.parseArray(authUserRecords);

        for(int i=0;i<jsonArray.size();i++ ) {
            AuthUserRecordInfo authUserRecordInfo=new AuthUserRecordInfo();
            JSONObject jsonObject = (JSONObject) jsonArray.get(i);
            JSONArray resourceInfos = jsonObject.getJSONArray("resourceInfos");


            authUserRecordInfo.setAuthUserRecordName(jsonObject.get("authUserRecordName").toString());
            List<TreeInfo> treeInfoss=new  ArrayList<>();
            for(int j=0;j<resourceInfos.size();j++ ) {
                TreeInfo treeInfo=new TreeInfo();
                JSONObject faceObj = (JSONObject) resourceInfos.get(j);
                treeInfo.setId(Integer.valueOf(faceObj.get("id").toString()));
                treeInfo.setIsResource(Integer.valueOf(faceObj.get("isResource").toString()) );
                if (!StringUtils.isEmpty(faceObj.get("parentId"))){
                    treeInfo.setParentId(Integer.valueOf(faceObj.get("parentId").toString()));
                }
                treeInfoss.add(treeInfo);
            }

            JSONArray subjectInfos = jsonObject.getJSONArray("subjectInfos");
            List<TreeInfo> treeInfoList = new  ArrayList<>();
            for(int j=0;j<subjectInfos.size();j++ ) {
                TreeInfo treeInfo=new TreeInfo();
                JSONObject faceObj = (JSONObject) subjectInfos.get(j);
                treeInfo.setId(Integer.valueOf(faceObj.get("id").toString()));
                treeInfo.setIsResource(Integer.valueOf(faceObj.get("isResource").toString()) );
                treeInfoList.add(treeInfo);
            }
            authUserRecordInfo.setResourceInfos(treeInfoss);
            authUserRecordInfo.setSubjectInfos(treeInfoList);
            authUserRecordInfoList.add(authUserRecordInfo);
        }
        return authUserRecordInfoList;
    }


    @Override
    public void deletePlan(Integer id) throws Exception {
        //删除预案
        emergencyPlanMapper.deletePlan(id);
        emergencyPlanMapper.deletePlanResource(id);
    }

    @Override
    public AuthUserRecords getRecordListByPlanId(Integer id) throws Exception {
        List<EmergencyRecordOrgResource> list = emergencyPlanMapper.getRecordListByPlanId(id);
        AuthUserRecords authUserRecords = new AuthUserRecords();
        //判断
        if(CollectionUtils.isEmpty(list)){
            return null;
        }
        //预案授权记录名称
        authUserRecords.setAuthUserRecordId(String.valueOf(list.get(0).getPlanId()));
        authUserRecords.setAuthUserRecordName(list.get(0).getAuthUserRecordName());

        //资源树组织机构节点字符串（逗号隔开的组织机构id数组）
        List<String> listAllOrg = new ArrayList<>();
        for (EmergencyRecordOrgResource model :list){
            String allOrg = model.getAllOrg();
            String[] split = allOrg.split(",");
            List<String> listitem =  Arrays.asList(split);
            listAllOrg.addAll(listitem);
        }
        authUserRecords.setResourceOrganizationIds(  Joiner.on(",").join(listAllOrg));

        //资源树摄像机节点字符串（逗号隔开的摄像机id数组）
        List<String> listcameraOrgId = new ArrayList<>();
        for (EmergencyRecordOrgResource model :list){
           if (model.getIsResource() == 1){
                //摄像机
               long cameraOrgId = model.getCameraOrgId();
               listcameraOrgId.add(String.valueOf(cameraOrgId));
           }
        }
        List<String> getcameraId = emergencyPlanMapper.getcameraId(listAllOrg);
        listcameraOrgId.addAll(getcameraId);
        authUserRecords.setResourceIds(Joiner.on(",").join(listcameraOrgId));

        //用户树组织机构节点字符串（逗号隔开的组织机构id数组）
        List<String> listOrgId = new ArrayList<>();
        for (EmergencyRecordOrgResource model :list){
            String userId = model.getUserId();
            if(StringUtils.isEmpty(userId)){
                continue;
            }
            List<String> strings = Arrays.asList(userId.split(","));
            //根据用户找组织
            for (String user : strings){
                String orgId = emergencyPlanMapper.getUserOrg(user);
                listOrgId.add(orgId);
            }
        }
        authUserRecords.setOrganizationIds(Joiner.on(",").join(listOrgId));

        return authUserRecords;

    }


    @Override
    public void updatePlan(Map<String, Object> paramMap) throws Exception{
        //删除预案
        String planId = String.valueOf(paramMap.get("planId"));
        deletePlan(Integer.valueOf(planId));
        //新增预案
        addPlan(paramMap);
    }
}
